package com.ds.robot.assistant.job;

import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.ds.robot.assistant.entity.ProjectInfoEntity;
import com.ds.robot.assistant.service.ProjectInfoService;
import com.ds.robot.assistant.util.JsonUtil;
import com.ds.robot.assistant.service.yunxiao.YunXiaoProjectClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Service
@Slf4j
@SuppressWarnings("ALL")
public class YunXiaoProjectJob {

    @Autowired
    private YunXiaoProjectClient yunXiaoProjectClient;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Resource
    private LoadingCache<String, ProjectInfoEntity> projectCache;

    @PostConstruct
    public void init() {
        updateProjectCache();
    }

    @Scheduled(cron = "0 5 0/8 * * *")
    @Transactional(rollbackFor = Exception.class)
    public void updateProjectJob() throws Exception {
        List<ProjectInfoEntity> projectList = yunXiaoProjectClient.queryProjectList();
        if (CollectionUtils.isEmpty(projectList)) {
            log.warn("查询云效项目为空，任务结束");
            return;
        }
        List<ProjectInfoEntity> dbList = projectInfoService.list();
        Map<String, ProjectInfoEntity> entityMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(dbList)) {
            entityMap = dbList.stream().collect(Collectors.toMap(ProjectInfoEntity::getSpaceId, Function.identity()));
        }

        List<ProjectInfoEntity> needSaveList = Lists.newArrayList();
        List<ProjectInfoEntity> needUpdateList = Lists.newArrayList();
        List<String> idList = projectList.stream().map(ProjectInfoEntity::getSpaceId).collect(Collectors.toList());
        List<String> needDeleteList = entityMap.keySet().stream().filter(id -> !idList.contains(id)).collect(Collectors.toList());

        for (ProjectInfoEntity project : projectList) {
            if (!entityMap.containsKey(project.getSpaceId())) {
                needSaveList.add(project);
            } else {
                ProjectInfoEntity projectDB = entityMap.get(project.getSpaceId());
                if (!projectDB.equals(project)) {
                    project.setId(projectDB.getId());
                    needUpdateList.add(project);
                }
            }
        }

        if (!CollectionUtils.isEmpty(needSaveList)) {
            boolean b = projectInfoService.saveBatch(needSaveList);
            log.info("批量新增项目成功? {}，数量={}", b, needSaveList.size());
        }
        if (!CollectionUtils.isEmpty(needUpdateList)) {
            log.info("需要更新的项目：{}", JsonUtil.toJson(needUpdateList));
            boolean b = projectInfoService.saveOrUpdateBatch(needUpdateList);
            log.info("批量更新项目成功? {}，数量={}", b, needUpdateList.size());
        }
        if (!CollectionUtils.isEmpty(needDeleteList)) {
            log.info("需要删除的项目：{}", JsonUtil.toJson(needDeleteList));
            boolean b = projectInfoService.lambdaUpdate().in(ProjectInfoEntity::getSpaceId, needDeleteList).remove();
            log.info("批量删除项目成功? {}，数量={}", b, needUpdateList.size());
        }
    }

    @Scheduled(cron = "0 15 0/8 * * *")
    public void updateProjectCache() {
        log.info("==== 开始更新ProjectCache");
        List<ProjectInfoEntity> projectList = projectInfoService.list();
        if (!CollectionUtils.isEmpty(projectList)) {
            for (ProjectInfoEntity entity : projectList) {
                projectCache.put(entity.getSpaceId(), entity);
            }
        }
        log.info("==== 更新ProjectCache完成");
    }

}
